package com.itlong.cloud.controller.settings;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.DTO.common.PadFaceSyncDataDTO;
import com.itlong.cloud.POJO.DTO.property.PropertyDeviceCloudControllerGetDTO;
import com.itlong.cloud.POJO.DTO.property.PropertyDeviceCloudControllerSaveDTO;
import com.itlong.cloud.POJO.PO.ProjectPO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.property.PropertyDeviceCloudControllerEleVO;
import com.itlong.cloud.POJO.VO.property.PropertyDeviceCloudControllerGetVO;
import com.itlong.cloud.POJO.VO.property.PropertyDeviceElevatorConfigVO;
import com.itlong.cloud.POJO.VO.property.PropertyRoleProjectGetVO;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.annotation.AuthAccessRequired;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.PropertyErrorCodeEnum;
import com.itlong.cloud.equip.property.IDeviceCloudControllerServiceClient;
import com.itlong.cloud.equip.property.IPadFaceSyncDataServiceClient;
import com.itlong.cloud.equip.property.IPropertyEquipServiceClient;
import com.itlong.cloud.project.operate.IOperateProjectServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.encrypt.DesEncryptUtil;
import com.itlong.cloud.utils.encrypt.Md5EncryptUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.words.NumberHandlerUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <desc>
 *      云群控器控制器
 * </desc>
 *
 * @createDate 2019/03/26
 */
@RestController
@RequestMapping("/settings/cloudController")
public class PropertyDeviceCloudController extends BaseController {

    private static Logger LOG = LoggerFactory.getLogger(PropertyDeviceCloudController.class);

    @Autowired
    private IDeviceCloudControllerServiceClient iDeviceCloudControllerServiceClient;

    //物业项目服务层暴露接口
    @Autowired
    private IOperateProjectServiceClient iOperateProjectServiceClient;

    //物业设备服务层暴露接口
    @Autowired
    private IPropertyEquipServiceClient iPropertyEquipServiceClient;

    @Autowired
    private IPadFaceSyncDataServiceClient iPadFaceSyncDataServiceClient;

    /**
     * <desc>
     *      分页查询云群控器列表
     * </desc>
     *
     * @param propertyDeviceCloudControllerGetDTO 云群控器查询DTO
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2019/03/26
     */
    @ResponseBody
    @AuthAccessRequired
    @PostMapping("getPage")
    public Object getPage(PropertyDeviceCloudControllerGetDTO propertyDeviceCloudControllerGetDTO){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyDeviceCloudControllerGetDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyDeviceCloudControllerGetDTO.class, request);
            if (propertyDeviceCloudControllerGetDTO == null) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isBlank(propertyDeviceCloudControllerGetDTO.getProjectId())) {
                return new MessageVO(PropertyErrorCodeEnum.PUB_PROJECT_ID_EMPTY_ERR.getErrorCode());
            }
            Page<PropertyDeviceCloudControllerGetVO> propertyDeviceCloudControllerGetVOPage = iDeviceCloudControllerServiceClient.getPage(propertyDeviceCloudControllerGetDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),propertyDeviceCloudControllerGetVOPage);
        } catch (Exception e) {
            throw new DataAccessException("【物业_系统_设备管理】查询云群控器列表失败", e);
        }
    }

    /**
     * <desc>
     *      查询单个云群控器
     * </desc>
     *
     * @param propertyDeviceCloudControllerGetDTO 云群控器查询DTO
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2019/03/27
     */
    @ResponseBody
    @PostMapping("getOne")
    public Object getOne(PropertyDeviceCloudControllerGetDTO propertyDeviceCloudControllerGetDTO){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyDeviceCloudControllerGetDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyDeviceCloudControllerGetDTO.class, request);
            if (propertyDeviceCloudControllerGetDTO == null) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isBlank(propertyDeviceCloudControllerGetDTO.getProjectId())) {
                return new MessageVO(PropertyErrorCodeEnum.PUB_PROJECT_ID_EMPTY_ERR.getErrorCode());
            }
            if (StringUtils.isBlank(propertyDeviceCloudControllerGetDTO.getDeviceName()) && StringUtils.isBlank(propertyDeviceCloudControllerGetDTO.getDeviceId())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isNotBlank(propertyDeviceCloudControllerGetDTO.getDeviceId())) {
                String deviceId = StringHandlerUtil.formatStrLen(propertyDeviceCloudControllerGetDTO.getDeviceId(), "0", 4, false, false);
                propertyDeviceCloudControllerGetDTO.setDeviceId(deviceId);
            }
            PropertyDeviceCloudControllerGetVO propertyDeviceCloudControllerGetVO = iDeviceCloudControllerServiceClient.getOne(propertyDeviceCloudControllerGetDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),propertyDeviceCloudControllerGetVO);
        } catch (Exception e) {
            throw new DataAccessException("【物业_系统_设备管理】查询单个云群控器失败", e);
        }
    }

    /**
     * <desc>
     *      一键启用禁用设备
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2019/03/27
     */
    @ResponseBody
    @PostMapping("setStatus")
    @LoggerInfo(operateDesc = LogDescConstant.DEVICE_CLOUD_CONTROLLER_SET_STATUS_LOG_DESC)
    @AuthAccessRequired
    public Object setStatus(String projectId,String deviceUnique,Integer status){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            projectId = request.getAttribute("projectId") == null ? null : request.getAttribute("projectId").toString();
            deviceUnique = request.getAttribute("deviceUnique") == null ? null : request.getAttribute("deviceUnique").toString();
            status = request.getAttribute("status") == null ? null : (Integer) request.getAttribute("status");
            if (StringUtils.isBlank(projectId)) {
                return new MessageVO(PropertyErrorCodeEnum.PUB_PROJECT_ID_EMPTY_ERR.getErrorCode());
            }
            if (StringUtils.isBlank(deviceUnique) || status == null) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (!NumberHandlerUtil.isInRange(status, 1, 2)) {
                return new MessageVO(BaseErrorCodeEnum.PARAM_ERR.getErrorCode());
            }
            iDeviceCloudControllerServiceClient.setStatus(projectId,deviceUnique,status);
            return new MessageVO(deviceUnique,BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【物业_系统_设备管理】一键启用禁用设备失败", e);
        }
    }

    /**
     * <desc>
     *      获取云群控器可绑定的云电梯设备列表信息
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2019/03/27
     */
    @ResponseBody
    @PostMapping("getCloudElevatorList")
    public Object getCloudElevatorList(PropertyDeviceCloudControllerGetDTO propertyDeviceCloudControllerGetDTO){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyDeviceCloudControllerGetDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyDeviceCloudControllerGetDTO.class, request);
            if (propertyDeviceCloudControllerGetDTO == null || StringUtils.isBlank(propertyDeviceCloudControllerGetDTO.getBuildId())
                    || StringUtils.isBlank(propertyDeviceCloudControllerGetDTO.getUnitId())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isBlank(propertyDeviceCloudControllerGetDTO.getProjectId())) {
                return new MessageVO(PropertyErrorCodeEnum.PUB_PROJECT_ID_EMPTY_ERR.getErrorCode());
            }
            List<PropertyDeviceCloudControllerEleVO> propertyDeviceCloudControllerEleVOS = iDeviceCloudControllerServiceClient.getCloudElevatorList(propertyDeviceCloudControllerGetDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),propertyDeviceCloudControllerEleVOS);
        } catch (Exception e) {
            throw new DataAccessException("【物业_系统_设备管理】获取电梯设备列表信息失败", e);
        }
    }

    /**
     * <desc>
     *      添加云群控器设备信息
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2019/03/27
     */
    @ResponseBody
    @PostMapping("save")
    @LoggerInfo(operateDesc = LogDescConstant.DEVICE_CLOUD_CONTROLLER_SAVE_LOG_DESC)
    @AuthAccessRequired
    public Object save(PropertyDeviceCloudControllerSaveDTO propertyDeviceCloudControllerSaveDTO){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyDeviceCloudControllerSaveDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyDeviceCloudControllerSaveDTO.class, request);
            // 校验参数合法性
            if (propertyDeviceCloudControllerSaveDTO == null || propertyDeviceCloudControllerSaveDTO.getResetStatus() == null ||
                    StringUtils.isBlank(propertyDeviceCloudControllerSaveDTO.getDeviceName()) || StringUtils.isBlank(propertyDeviceCloudControllerSaveDTO.getDeviceId())
                    || StringUtils.isBlank(propertyDeviceCloudControllerSaveDTO.getBuildId()) || StringUtils.isBlank(propertyDeviceCloudControllerSaveDTO.getUnitId())
                    || StringUtils.isBlank(propertyDeviceCloudControllerSaveDTO.getDeviceUniqueElevators())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isBlank(propertyDeviceCloudControllerSaveDTO.getProjectId())) {
                return new MessageVO(PropertyErrorCodeEnum.PUB_PROJECT_ID_EMPTY_ERR.getErrorCode());
            }
            if (!NumberHandlerUtil.isInRange(propertyDeviceCloudControllerSaveDTO.getResetStatus(),0,2) || propertyDeviceCloudControllerSaveDTO.getDeviceName().length() > 20) {
                return new MessageVO(BaseErrorCodeEnum.PARAM_ERR.getErrorCode());
            }
            if (propertyDeviceCloudControllerSaveDTO.getResetStatus() == 1 && StringUtils.isBlank(propertyDeviceCloudControllerSaveDTO.getResetDeviceUnique())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isNotBlank(propertyDeviceCloudControllerSaveDTO.getDeviceMemo()) && propertyDeviceCloudControllerSaveDTO.getDeviceMemo().length() > 50) {
                return new MessageVO(BaseErrorCodeEnum.PARAM_ERR.getErrorCode());
            }
            if (StringHandlerUtil.strToIntDef(propertyDeviceCloudControllerSaveDTO.getDeviceId(), -1) == -1) {
                return new MessageVO(BaseErrorCodeEnum.PARAM_ERR.getErrorCode());
            }
            // 校验唯一性
            PropertyDeviceCloudControllerGetDTO propertyDeviceCloudControllerGetDTO = new PropertyDeviceCloudControllerGetDTO();
            propertyDeviceCloudControllerGetDTO.setProjectId(propertyDeviceCloudControllerSaveDTO.getProjectId());
            propertyDeviceCloudControllerGetDTO.setDeviceName(propertyDeviceCloudControllerSaveDTO.getDeviceName());
            PropertyDeviceCloudControllerGetVO oneByName = iDeviceCloudControllerServiceClient.getOne(propertyDeviceCloudControllerGetDTO);
            if (oneByName != null) {
                return new MessageVO(PropertyErrorCodeEnum.EQUIP_DEVICENAME_IS_EXIST.getErrorCode());
            }
            propertyDeviceCloudControllerGetDTO.setDeviceName(null);
            propertyDeviceCloudControllerGetDTO.setDeviceId(StringHandlerUtil.formatStrLen(propertyDeviceCloudControllerSaveDTO.getDeviceId(),"0", 4, false, false));
            PropertyDeviceCloudControllerGetVO oneByDeviceId = iDeviceCloudControllerServiceClient.getOne(propertyDeviceCloudControllerGetDTO);
            if (oneByDeviceId != null) {
                return new MessageVO(PropertyErrorCodeEnum.EQUIP_DEVICEID_IS_EXIST.getErrorCode());
            }
            // 校验云群控器和云电梯是否正在执行预约，0否，1是
//            int callStatus = iDeviceCloudControllerServiceClient.checkCloudCallStatus(propertyDeviceCloudControllerSaveDTO);
//            if (callStatus == 1) {
//                return new MessageVO(PropertyErrorCodeEnum.DEVICE_CALL_STATUS_ERR.getErrorCode());
//            }
            int sync = 0;
            if (propertyDeviceCloudControllerSaveDTO.getResetStatus() == 0) {
                // 校验所选云电梯的楼层映射表，0-楼层对应表不一致，1-楼层对应表一致
                int flag = iDeviceCloudControllerServiceClient.checkElevatorFloorConfig(propertyDeviceCloudControllerSaveDTO.getDeviceUniqueElevators());
                if (flag == 0) {
                    return new MessageVO(PropertyErrorCodeEnum.ELEVATOR_FLOOR_CONFIG_DIFFERENT_ERR.getErrorCode());
                }
                //校验所选云电梯的公共楼层是否一致
                int commonFloorFlag = iDeviceCloudControllerServiceClient.checkElevatorCommonFloorConfig(propertyDeviceCloudControllerSaveDTO.getDeviceUniqueElevators());
                if (commonFloorFlag == 0) {
                    return new MessageVO(PropertyErrorCodeEnum.ELEVATOR_COMMON_FLOOR_CONFIG_DIFFERENT_ERR.getErrorCode());
                }
            } else if(propertyDeviceCloudControllerSaveDTO.getResetStatus() == 2){
                iDeviceCloudControllerServiceClient.resetElevatorCommonFloorConfig(propertyDeviceCloudControllerSaveDTO);
            } else {
                // 同步楼层映射表
                int flag = iDeviceCloudControllerServiceClient.resetElevatorFloorConfig(propertyDeviceCloudControllerSaveDTO);
                if (flag == 0) {
                    return new MessageVO(BaseErrorCodeEnum.ERROR.getErrorCode());
                }
                // 楼层映射表改动，做对应操作，后续rebase V1.7.9和V1.8.1版本后有其它内容需要加上
                // 云对讲SDK的内容
                this.updateToUrl(propertyDeviceCloudControllerSaveDTO.getDeviceUniqueElevators(),propertyDeviceCloudControllerSaveDTO.getProjectId());
                //查询当前项目信息
                ProjectPO projectPO = iOperateProjectServiceClient.getOneProject(propertyDeviceCloudControllerSaveDTO.getProjectId());
                // 平板优先离线，则插入同步数据
                if (projectPO.getOnOffLinePadFace() != null) {
                    PadFaceSyncDataDTO padFaceSyncDataDTO = new PadFaceSyncDataDTO();
                    padFaceSyncDataDTO.setOperateType("2");
                    padFaceSyncDataDTO.setDeviceUniques(propertyDeviceCloudControllerSaveDTO.getDeviceUniqueElevators());
                    padFaceSyncDataDTO.setProjectId(propertyDeviceCloudControllerSaveDTO.getProjectId());
                    padFaceSyncDataDTO.setStatus("1");
                    padFaceSyncDataDTO.setSourceSystem(2);
                    if(projectPO.getOnOffLinePadFace() == 1){
                        iPadFaceSyncDataServiceClient.userOrFloorSync(padFaceSyncDataDTO);
                    }
                    iPadFaceSyncDataServiceClient.userOrFloorSyncSmartCard(padFaceSyncDataDTO);
                    sync = 1;
                }
            }
            // 格式化设备机号
            String deviceId = StringHandlerUtil.formatStrLen(propertyDeviceCloudControllerSaveDTO.getDeviceId(),"0", 4, false, false);
            propertyDeviceCloudControllerSaveDTO.setDeviceId(deviceId);
            // 拼接设备序列号
            String deviceUnique = propertyDeviceCloudControllerSaveDTO.getProjectId() + "5" + propertyDeviceCloudControllerSaveDTO.getDeviceId();
            propertyDeviceCloudControllerSaveDTO.setDeviceUnique(deviceUnique);
            // 拼接设备sn
            String sn = propertyDeviceCloudControllerSaveDTO.getProjectId() + "0000" + propertyDeviceCloudControllerSaveDTO.getDeviceId();
            propertyDeviceCloudControllerSaveDTO.setSn(sn);
            iDeviceCloudControllerServiceClient.save(propertyDeviceCloudControllerSaveDTO);
            if (sync == 1) {
                PadFaceSyncDataDTO padFaceSyncDataDTO = new PadFaceSyncDataDTO();
                padFaceSyncDataDTO.setOperateType("4");
                padFaceSyncDataDTO.setDeviceUniques(propertyDeviceCloudControllerSaveDTO.getDeviceUnique());
                padFaceSyncDataDTO.setProjectId(propertyDeviceCloudControllerSaveDTO.getProjectId());
                iPadFaceSyncDataServiceClient.userOrFloorSyncSmartCard(padFaceSyncDataDTO);
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【物业_系统_设备管理】添加云群控器设备信息失败", e);
        }
    }

    /**
     * <desc>
     *      修改云群控器设备信息
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2019/03/28
     */
    @ResponseBody
    @PostMapping("update")
    @LoggerInfo(operateDesc = LogDescConstant.DEVICE_CLOUD_CONTROLLER_UPDATE_LOG_DESC)
    @AuthAccessRequired
    public Object update(PropertyDeviceCloudControllerSaveDTO propertyDeviceCloudControllerSaveDTO){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyDeviceCloudControllerSaveDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyDeviceCloudControllerSaveDTO.class, request);
            // 校验参数合法性
            if (propertyDeviceCloudControllerSaveDTO == null || propertyDeviceCloudControllerSaveDTO.getResetStatus() == null ||
                    StringUtils.isBlank(propertyDeviceCloudControllerSaveDTO.getDeviceName()) || StringUtils.isBlank(propertyDeviceCloudControllerSaveDTO.getDeviceUnique())
                    || StringUtils.isBlank(propertyDeviceCloudControllerSaveDTO.getBuildId()) || StringUtils.isBlank(propertyDeviceCloudControllerSaveDTO.getUnitId())
                    || StringUtils.isBlank(propertyDeviceCloudControllerSaveDTO.getDeviceUniqueElevators())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isBlank(propertyDeviceCloudControllerSaveDTO.getProjectId())) {
                return new MessageVO(PropertyErrorCodeEnum.PUB_PROJECT_ID_EMPTY_ERR.getErrorCode());
            }
            if (!NumberHandlerUtil.isInRange(propertyDeviceCloudControllerSaveDTO.getResetStatus(),0,2) || propertyDeviceCloudControllerSaveDTO.getDeviceName().length() > 20) {
                return new MessageVO(BaseErrorCodeEnum.PARAM_ERR.getErrorCode());
            }
            if (propertyDeviceCloudControllerSaveDTO.getResetStatus() == 1 && StringUtils.isBlank(propertyDeviceCloudControllerSaveDTO.getResetDeviceUnique())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isNotBlank(propertyDeviceCloudControllerSaveDTO.getDeviceMemo()) && propertyDeviceCloudControllerSaveDTO.getDeviceMemo().length() > 50) {
                return new MessageVO(BaseErrorCodeEnum.PARAM_ERR.getErrorCode());
            }
            propertyDeviceCloudControllerSaveDTO.setDeviceId(null);
            propertyDeviceCloudControllerSaveDTO.setSn(null);
            // 校验唯一性
            PropertyDeviceCloudControllerGetDTO propertyDeviceCloudControllerGetDTO = new PropertyDeviceCloudControllerGetDTO();
            propertyDeviceCloudControllerGetDTO.setProjectId(propertyDeviceCloudControllerSaveDTO.getProjectId());
            propertyDeviceCloudControllerGetDTO.setDeviceName(propertyDeviceCloudControllerSaveDTO.getDeviceName());
            PropertyDeviceCloudControllerGetVO oneByName = iDeviceCloudControllerServiceClient.getOne(propertyDeviceCloudControllerGetDTO);
            if (oneByName != null && !oneByName.getDeviceUnique().equals(propertyDeviceCloudControllerSaveDTO.getDeviceUnique())) {
                return new MessageVO(PropertyErrorCodeEnum.EQUIP_DEVICENAME_IS_EXIST.getErrorCode());
            }
            // 校验云群控器和云电梯是否正在执行预约，0否，1是
//            int callStatus = iDeviceCloudControllerServiceClient.checkCloudCallStatus(propertyDeviceCloudControllerSaveDTO);
//            if (callStatus == 1) {
//                return new MessageVO(PropertyErrorCodeEnum.DEVICE_CALL_STATUS_ERR.getErrorCode());
//            }
            int sync = 0;
            if (propertyDeviceCloudControllerSaveDTO.getResetStatus() == 0) {
                // 校验所选云电梯的楼层映射表，0-楼层对应表不一致，1-楼层对应表一致
                int flag = iDeviceCloudControllerServiceClient.checkElevatorFloorConfig(propertyDeviceCloudControllerSaveDTO.getDeviceUniqueElevators());
                if (flag == 0) {
                    return new MessageVO(PropertyErrorCodeEnum.ELEVATOR_FLOOR_CONFIG_DIFFERENT_ERR.getErrorCode());
                }                //校验所选云电梯的公共楼层是否一致
                int commonFloorFlag = iDeviceCloudControllerServiceClient.checkElevatorCommonFloorConfig(propertyDeviceCloudControllerSaveDTO.getDeviceUniqueElevators());
                if (commonFloorFlag == 0) {
                    return new MessageVO(PropertyErrorCodeEnum.ELEVATOR_COMMON_FLOOR_CONFIG_DIFFERENT_ERR.getErrorCode());
                }
            } else if(propertyDeviceCloudControllerSaveDTO.getResetStatus() == 2){
                iDeviceCloudControllerServiceClient.resetElevatorCommonFloorConfig(propertyDeviceCloudControllerSaveDTO);
            } else {
                // 同步楼层映射表
                int flag = iDeviceCloudControllerServiceClient.resetElevatorFloorConfig(propertyDeviceCloudControllerSaveDTO);
                if (flag == 0) {
                    return new MessageVO(BaseErrorCodeEnum.ERROR.getErrorCode());
                }
                // 楼层映射表改动，做对应操作，后续rebase V1.7.9和V1.8.1版本后有其它内容需要加上
                // 云对讲SDK的内容
                this.updateToUrl(propertyDeviceCloudControllerSaveDTO.getDeviceUniqueElevators(),propertyDeviceCloudControllerSaveDTO.getProjectId());
                //查询当前项目信息
                ProjectPO projectPO = iOperateProjectServiceClient.getOneProject(propertyDeviceCloudControllerSaveDTO.getProjectId());
                // 平板优先离线，则插入同步数据
                if (projectPO.getOnOffLinePadFace() != null) {
                    PadFaceSyncDataDTO padFaceSyncDataDTO = new PadFaceSyncDataDTO();
                    padFaceSyncDataDTO.setOperateType("2");
                    padFaceSyncDataDTO.setDeviceUniques(propertyDeviceCloudControllerSaveDTO.getDeviceUniqueElevators());
                    padFaceSyncDataDTO.setProjectId(propertyDeviceCloudControllerSaveDTO.getProjectId());
                    padFaceSyncDataDTO.setStatus("1");
                    padFaceSyncDataDTO.setSourceSystem(2);
                    if(projectPO.getOnOffLinePadFace() == 1){
                        iPadFaceSyncDataServiceClient.userOrFloorSync(padFaceSyncDataDTO);
                    }
                    iPadFaceSyncDataServiceClient.userOrFloorSyncSmartCard(padFaceSyncDataDTO);
                    sync = 1;
                }
            }
            if (sync == 1) {
                PadFaceSyncDataDTO padFaceSyncDataDTO = new PadFaceSyncDataDTO();
                padFaceSyncDataDTO.setOperateType("4");
                padFaceSyncDataDTO.setDeviceUniques(propertyDeviceCloudControllerSaveDTO.getDeviceUnique());
                padFaceSyncDataDTO.setProjectId(propertyDeviceCloudControllerSaveDTO.getProjectId());
                iPadFaceSyncDataServiceClient.userOrFloorSyncSmartCard(padFaceSyncDataDTO);
            }
            iDeviceCloudControllerServiceClient.update(propertyDeviceCloudControllerSaveDTO);
            return new MessageVO(propertyDeviceCloudControllerSaveDTO.getDeviceUnique(),BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【物业_系统_设备管理】修改云群控器设备信息失败", e);
        }
    }


    /**
     * <desc>
     *      云电梯SDK第三方云端上报设备信息变更后接口数据结构说明
     * </desc>
     *
     * @param deviceUniqueStr 设备序列号，多个英文逗号相连
     * @param projectId 项目id
     * @author wangzhi
     * @createDate 2019/01/21
     */
    private void updateToUrl(String deviceUniqueStr,String projectId){
        new Thread(() -> {
            try {
                List<String> deviceUniqueList = StringHandlerUtil.splitStringList(deviceUniqueStr);
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                Date date = new Date();
                String createTime = df.format(date);//签名用时间
                List<PropertyRoleProjectGetVO> propertyRoleProjectGetVOS = iOperateProjectServiceClient.getRoleProjectInfo(projectId);
                if (propertyRoleProjectGetVOS == null || propertyRoleProjectGetVOS.isEmpty()) {
                    return;
                }
                for (PropertyRoleProjectGetVO propertyRoleProjectGetVO : propertyRoleProjectGetVOS) {
                    if (propertyRoleProjectGetVO == null || StringUtils.isBlank(propertyRoleProjectGetVO.getUpdateInfoUrl())
                            || StringUtils.isBlank(propertyRoleProjectGetVO.getAppSecret()) || StringUtils.isBlank(propertyRoleProjectGetVO.getAppId())) {
                        continue;
                    }
                    for (String deviceUnique : deviceUniqueList){
                        PropertyDeviceElevatorConfigVO propertyDeviceElevatorConfigVO = iPropertyEquipServiceClient.getDeviceElevatorConfig(deviceUnique);
                        if (propertyDeviceElevatorConfigVO == null || StringUtils.isBlank(propertyDeviceElevatorConfigVO.getDeviceUnique())) {
                            continue;
                        }
                        JSONObject json = new JSONObject();
                        json.put("deviceUnique", propertyDeviceElevatorConfigVO.getDeviceUnique());
                        json.put("logicalFloor ", propertyDeviceElevatorConfigVO.getLogicalFloor());
                        json.put("floorNum", propertyDeviceElevatorConfigVO.getFloorNum());
                        Map<String, Object> jsonToMap = JsonUtil.JsonToMap(json.toJSONString());
                        String sign = Md5EncryptUtil.cloudDeviceMd5(jsonToMap, createTime, propertyRoleProjectGetVO.getAppSecret());
                        //LOG.info(deviceUnique + "的sign：" + sign);
                        // 加密前先将createTime传入方法,最后在将createTime和sign放入json中
                        json.put("createTime", createTime);
                        json.put("sign", sign);
                        //LOG.info(deviceUnique + "加密前的参数：" + json);
                        String encryptResult = DesEncryptUtil.aesEncryptSDK(json.toJSONString(), propertyRoleProjectGetVO.getAppSecret());
                        //LOG.info(deviceUnique + "加密后的参数：" + encryptResult);
                        String encryptReturn = HttpProtocolUtil.httpPost(propertyRoleProjectGetVO.getUpdateInfoUrl(), "encryptScript=" + encryptResult);
                        String result = DesEncryptUtil.aesDecrypt(encryptReturn, propertyRoleProjectGetVO.getAppSecret());
                        // 处理结果：0正常 1错误
                        JSONObject jsonObject = JSON.parseObject(result);
                        if ("0".equals(jsonObject.getString("result"))) {
                            //LOG.info(deviceUnique + "上报成功，返回值为：" + result);
                        } else {
                            LOG.info(deviceUnique + "上报失败，返回值为：" + result);
                        }
                    }
                }
            } catch (Exception e) {
                LOG.error("【第三方云端上报设备信息(楼层映射表信息)变更后接口数据结构说明失败】",e);
            }
        }).start();
    }

    /**
     * <desc>
     *      获取群控器设备详情
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author Jiaqi.X
     * @createDate 2019/08/13
     */
    @ResponseBody
    @AuthAccessRequired
    @PostMapping("deviceInfo")
    public Object deviceInfo(String deviceUnique){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            deviceUnique = request.getAttribute("deviceUnique") == null ? null : request.getAttribute("deviceUnique").toString();
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),iDeviceCloudControllerServiceClient.getControllerFloorInfo(deviceUnique));
        } catch (Exception e) {
            throw new DataAccessException("【物业_系统_设备管理】获取电梯设备列表信息失败", e);
        }
    }
}
